import {
  CustomDashboardController,
  DashboardController,
} from '@ibiz-template/runtime';
import { useNamespace } from '@ibiz-template/vue3-util';
import { IDashboard, IDBPortletPart } from '@ibiz/model-core';
import {
  computed,
  CSSProperties,
  defineComponent,
  onMounted,
  PropType,
  reactive,
  ref,
} from 'vue';
import './custom-dashboard-container.scss';

export const CustomDashboardContainer = defineComponent({
  name: 'IBizCustomDashboardContainer',
  props: {
    modelData: {
      type: Object as PropType<IDashboard>,
      required: true,
    },
    dashboard: {
      type: Object as PropType<DashboardController>,
      required: true,
    },
  },
  setup(props, { emit }) {
    const ns = useNamespace(`custom-dashboard-container`);

    const customC = reactive(new CustomDashboardController(props.modelData));

    // 是否初始化完成
    const isInited = ref(false);

    // 是否显示设计面板
    const isShowDesign = ref(false);

    // 工具栏收缩
    const showTypeDir = ref(false);

    // 打开设计面板
    const openDesign = () => {
      isShowDesign.value = true;
    };

    // 点击伸缩
    const clickCollapse = (type: string) => {
      showTypeDir.value = type === 'left';
    };

    // 根据codeName去全局获取portlet模型
    const getPortletByCodeName = (
      codeName: string,
    ): IDBPortletPart | undefined => {
      const app = ibiz.hub.getApp(ibiz.env.appId);
      if (app.model.appPortlets) {
        const appPortlet = app.model.appPortlets.find(portlet => {
          return portlet.control?.codeName === codeName;
        });
        if (appPortlet) {
          return appPortlet.control as IDBPortletPart;
        }
      }
    };

    // 根据自定义数据获取模型数组
    const convertData = (models: IData[]) => {
      const tempModelDatas: IDBPortletPart[] = [];
      if (models.length > 0) {
        models.forEach((item: IData) => {
          const temModelData = getPortletByCodeName(item.portletCodeName);
          if (temModelData) {
            tempModelDatas.push(temModelData);
          }
        });
      }
      return tempModelDatas;
    };

    // 保存完成
    const onSaved = (args: IData) => {
      isShowDesign.value = false;
      const tempModelDatas: IDBPortletPart[] = convertData(args.model);
      emit('changed', { model: tempModelDatas });
    };

    // 是否显示默认插件
    const isShowDefault = computed(() => {
      return customC.customModelData.length === 0;
    });

    onMounted(async () => {
      const model = await customC.loadCustomModelData();
      const tempModelDatas: IDBPortletPart[] = convertData(model);
      emit('changed', { model: tempModelDatas });
      isInited.value = true;
    });

    return {
      ns,
      customC,
      isShowDesign,
      isInited,
      isShowDefault,
      showTypeDir,
      openDesign,
      onSaved,
      clickCollapse,
    };
  },

  render() {
    return (
      <div class={[this.ns.b()]}>
        <div class={this.ns.b('build-btn')}>
          {this.showTypeDir ? (
            <div>
              <el-button
                class={this.ns.b('deisgn-btn')}
                title={'门户定制'}
                onClick={this.openDesign}
              >
                <ion-icon name='build-outline'></ion-icon>
              </el-button>
              <el-button
                class={this.ns.b('forward-btn')}
                onClick={() => this.clickCollapse('right')}
              >
                <ion-icon name='chevron-forward-outline'></ion-icon>
              </el-button>
            </div>
          ) : (
            <el-button
              class={this.ns.b('back-btn')}
              onClick={() => this.clickCollapse('left')}
            >
              <ion-icon name='chevron-back-outline'></ion-icon>
            </el-button>
          )}
        </div>
        <el-drawer
          v-model={this.isShowDesign}
          with-header={false}
          size='80%'
          modal-class={'custom-dashboard-drawer'}
        >
          {this.isShowDesign && (
            <iBizDashboardDesign
              dashboard={this.dashboard}
              custom-dashboard={this.customC}
              is-show-design={this.isShowDesign}
              onSaved={this.onSaved}
            />
          )}
        </el-drawer>
        {this.isInited &&
          (this.isShowDefault
            ? this.$slots.default?.()
            : this.customC.customModelData.map(item => {
                const itemStyle = {
                  position: 'absolute',
                  height: `${item.h * this.customC.layoutRowH}px`,
                  width: `calc(100% / ${this.customC.layoutColNum} * ${item.w})`,
                  top: `${item.y * this.customC.layoutRowH}px`,
                  left: `calc(100% / ${this.customC.layoutColNum} * ${item.x})`,
                } as CSSProperties;
                return (
                  <div style={itemStyle}>
                    {this.$slots[item.portletCodeName]?.()}
                  </div>
                );
              }))}
      </div>
    );
  },
});
